<template>
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="85%"
    draggable
    @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
      <div class="search-container">
        <el-row>
          <el-col :span="6">
            <el-form-item
              label="设定编号"
              style="width: 310px"
              prop="callSettingCode"
            >
              <span>{{ formData.callSettingCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="设定描述"
              style="width: 310px"
              prop="callSettingName"
            >
              <span>{{ formData.callSettingName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="公司"
              style="width: 290px"
              prop="organizationId"
            >
              <span>{{ formData.organizationCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="工厂" style="width: 310px" prop="plantId">
              <span> {{ formData.plantCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="呼叫类型" style="width: 310px" prop="plantId">
              <span> {{ formData.callTypeName }}</span>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="是否启用" style="width: 310px" prop="enabled">
              <span>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="创建时间"
              style="width: 310px"
              prop="createTime"
            >
              <span>{{ formData.createTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="创建人"
              style="width: 310px"
              prop="createdUserName"
            >
              <span>{{ formData.createdUserName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" style="width: 310px" prop="remarks">
              <span>{{ formData.remarks }}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
      <el-card shadow="never" class="table-container">
        <template #header>
          <el-button type="success" plain @click="handleAdd">
            <i-ep-plus />
            新增
          </el-button>
        </template>
        <div class="formTable">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              label="呼叫顺序号"
              props="callSequence"
              min-width="100"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.callSequence'"
                  :rules="rules.soncallSequence"
                  label-width="0"
                >
                  <el-input
                    v-model="row.callSequence"
                    placeholder="请输入呼叫顺序号"
                    @blur="changeDetailsSort(row)"
                    clearable
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="呼叫方式" props="callType" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.callType'"
                  :rules="rules.soncallType"
                  label-width="0"
                >
                  <el-select
                    v-model="row.callType"
                    clearable
                    filterable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="item in dictionaryStore.filterDictList(
                        'AndCallType'
                      )"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  <!--                  <span v-else>{{-->
                  <!--                      dictionaryStore.filterDictName("AndCallType", row.callType)-->
                  <!--                    }}</span>-->
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="未响应升级时间(min)"
              props="answerRaiseTime"
              min-width="160"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.answerRaiseTime'"
                  :rules="rules.sonanswerRaiseTime"
                  label-width="0"
                >
                  <el-input
                    v-model="row.answerRaiseTime"
                    placeholder="请输入未响应升级时间"
                    clearable
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="未到场升级时间(min)"
              props="arriveRaiseTime"
              min-width="160"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.arriveRaiseTime'"
                  :rules="rules.sonarriveRaiseTime"
                  label-width="0"
                >
                  <el-input
                    v-model="row.arriveRaiseTime"
                    placeholder="请输入未到场升级时间"
                    clearable
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="维修升级时间(min)"
              props="repairRaiseTime"
              min-width="145"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.repairRaiseTime'"
                  :rules="rules.sonrepairRaiseTime"
                  label-width="0"
                >
                  <el-input
                    v-model="row.repairRaiseTime"
                    placeholder="请输入维修升级时间"
                    clearable
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <!--            <el-table-column-->
            <!--              label="重复次数"-->
            <!--              props="repeatCount"-->
            <!--              min-width="100"-->
            <!--            >-->
            <!--              <template #default="{ $index, row }">-->
            <!--                <el-form-item :rules="rules.sonrepeatCount" label-width="0">-->
            <!--                  <el-input-->
            <!--                    v-model="row.repeatCount"-->
            <!--                    placeholder="请输入重复次数"-->
            <!--                    clearable-->
            <!--                  />-->
            <!--                </el-form-item>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column-->
            <!--              label="重复呼叫间隔"-->
            <!--              props="repeatInterval"-->
            <!--              min-width="120"-->
            <!--            >-->
            <!--              <template #default="{ $index, row }">-->
            <!--                <el-form-item :rules="rules.sonrepeatInterval" label-width="0">-->
            <!--                  <el-input-->
            <!--                    v-model="row.repeatInterval"-->
            <!--                    placeholder="请输入重复呼叫间隔"-->
            <!--                    clearable-->
            <!--                  />-->
            <!--                </el-form-item>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <el-table-column
              label="呼叫内容"
              props="callContent"
              min-width="150"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.callContent'"
                  :rules="rules.soncallContent"
                  label-width="0"
                >
                  <el-input
                    v-model="row.callContent"
                    placeholder="请输入呼叫内容"
                    clearable
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="班组" props="crewId" min-width="170">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.crewId'"
                  :rules="rules.soncrewId"
                  label-width="0"
                >
                  <el-select
                    v-model="row.crewId"
                    placeholder="请输入班组"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in crewList"
                      :key="item.id"
                      :label="`${item.crewCode}-${item.crewName}`"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="成员角色"
              props="memberRoleId"
              min-width="140"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'crewMembers.' + $index + '.memberRoleId'"
                  :rules="rules.memberRoleName"
                  label-width="0"
                >
                  <el-select
                    v-model="row.memberRoleId"
                    placeholder="请选择成员角色"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in memberRoleList"
                      :key="item.id"
                      :label="item.memberRoleName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="呼叫不在班人员"
              props="callOffDuty"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.callOffDuty'"
                  :rules="rules.soncallOffDuty"
                  label-width="0"
                >
                  <el-switch v-model="row.callOffDutyBool" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="用户id" props="userId" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item label-width="0" :rules="rules.sonuserId">
                  <SelectPerson-Member
                    :isMultiple="false"
                    :maxCollapseTags="5"
                    :showSelectPerson="row.users"
                    @get-person="
                      (id, object) => getDayPerson(id, object, $index)
                    "
                    :width="'100%'"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="备注" props="remarks" min-width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.remarks'"
                  :rules="rules.sonremarks"
                  label-width="0"
                >
                  <el-input
                    v-model="row.remarks"
                    placeholder="请输入备注"
                    clearable
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >确 定
        </el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "ANDCALLSETTINGDETAIL",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
let plants = ref([]);
let callTypes = ref([]);
//班组
const crewList = ref([]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  callSettingCode: "",
  callSettingName: "",
  organizationId: "",
  organizationCode: "",
  organizationName: "",
  plantId: "",
  plantCode: "",
  callTypeId: "",
  callTypeCode: "",
  callTypeName: "",
  crewId: "",
  crewCode: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  details: [
    {
      id: "",
      callSettingId: "",
      callSettingCode: "",
      callSequence: "",
      callType: "",
      repairRaiseTime: "",
      answerRaiseTime: "",
      arriveRaiseTime: "",
      repeatCount: "",
      repeatInterval: "",
      callContent: "",
      crewId: "",
      crewName: "",
      memberRoleId: "",
      memberRoleName: "",
      version: "",
      callRestRole: "",
      userId: "",
      users: [],
      userIduserName: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  soncallSettingId: [
    { required: true, message: "请输入安东呼叫设定id", trigger: "blur" },
  ],
  soncallSettingCode: [
    { required: true, message: "请输入安东呼叫设定编号", trigger: "blur" },
  ],
  soncallSequence: [
    { required: true, message: "请输入呼叫顺序号", trigger: "blur" },
    // { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  soncallType: [{ required: true, message: "请输入呼叫方式", trigger: "blur" }],
  soncrewId: [{ required: true, message: "请选择班组", trigger: "blur" }],
  sonrepairRaiseTime: [
    // { required: true, message: "请输入维修升级时间", trigger: "blur" },
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  sonanswerRaiseTime: [
    // { required: true, message: "请输入未响应升级时间", trigger: "blur" },
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  sonarriveRaiseTime: [
    // { required: true, message: "请输入未到场升级时间", trigger: "blur" },
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  sonrepeatCount: [
    // { required: true, message: "请输入重复次数", trigger: "blur" },
    { min: 1, max: 3, message: "长度在 1 到 3 个字符", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  sonrepeatInterval: [
    { required: true, message: "请输入重复呼叫间隔", trigger: "blur" },
    { min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur" },
    {
      pattern: /^(0|[1-9][0-9]*)$/,
      message: "只能请输入正整数",
      trigger: "blur",
    },
  ],
  soncallContent: [
    { required: true, message: "请输入呼叫内容", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  sonmemberRoleId: [
    { required: true, message: "请输入成员角色id", trigger: "blur" },
  ],
  sonmemberRoleName: [
    { required: true, message: "请输入成员角色名称", trigger: "blur" },
  ],
  sonversion: [
    { required: true, message: "请输入数据版本号", trigger: "blur" },
  ],
  soncallOffDuty: [],
  sonuserId: [{ required: true, message: "请输入用户id", trigger: "blur" }],
  sonuserIduserName: [
    { required: true, message: "请输入用户姓名", trigger: "blur" },
  ],
  sonremarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
  soncreateTime: [
    { required: true, message: "请输入创建时间", trigger: "blur" },
  ],
  soncreatedUserId: [
    { required: true, message: "请输入创建人", trigger: "blur" },
  ],
  soncreatedUserName: [
    { required: true, message: "请输入创建人名", trigger: "blur" },
  ],
  sonlastUpdateTime: [
    { required: true, message: "请输入更新时间", trigger: "blur" },
  ],
  sonlastUpdatedUserId: [
    { required: true, message: "请输入更新人", trigger: "blur" },
  ],
  sonlastUpdatedUserName: [
    { required: true, message: "请输入更新人名", trigger: "blur" },
  ],
  sonenabled: [{ required: true, message: "请输入是否启用", trigger: "blur" }],
  sondeleted: [{ required: true, message: "请输入删除标识", trigger: "blur" }],
});

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getCallTypes();
        getCrews();
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

const details = {
  id: "",
  callSettingId: "",
  callSettingCode: "",
  callSequence: "",
  callType: "",
  repairRaiseTime: "",
  answerRaiseTime: "",
  arriveRaiseTime: "",
  repeatCount: "",
  repeatInterval: "",
  callContent: "",
  memberRoleId: "",
  memberRoleName: "",
  callOffDuty: "",
  callOffDutyBool: false,
  version: "",
  callRestRole: "",
  userId: "",
  users: [],
  userIduserName: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.callSettingCode = "";
  formData.callSettingName = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.organizationName = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.callTypeId = "";
  formData.callTypeCode = "";
  formData.callTypeName = "";
  formData.crewId = "";
  formData.crewCode = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

function getSelectIds(ids) {
  formData.organizationId = ids;
  getPlants();
}

function organizationDataChange(datas: [] | {}) {
  formData.organizationName = datas.organizationName;
  formData.organizationCode = datas.organizationCode;
}

function plantChange() {
  var plant = plants.value.find((item) => {
    return item.id === formData.plantId;
  });
  formData.plantCode = plant.organizationCode;
  getCrews();
  getCallTypes();
}

function callChange() {
  var callType = callTypes.value.find((item) => {
    return item.id === formData.callTypeId;
  });
  formData.callTypeCode = callType.callTypeCode;
}

const loading = ref(false);
onMounted(() => {
  getPlants();
  memberRole();
});
const changeCrew = (id: any) => {
  formData.crewId = id;
  crewList.value.forEach((item) => {
    if (item.id === id) {
      formData.crewCode = item.crewCode;
      formData.crewName = item.crewName;
    }
  });
};

async function getCrews() {
  await request({
    url: "mes/mescrew/getCrew",
    method: "post",
    data: {
      plantId: formData.plantId,
      enabled: 1,
    },
  }).then((res) => {
    crewList.value = res.data;
  });
}

async function getPlants() {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
}

async function getCallTypes() {
  const data = await request({
    url: "/andon/andcalltype/querycalltypes",
    method: "post",
    data: { plantId: formData.plantId },
  });
  callTypes.value = data.data;
}

/** 角色保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = "保存";
      formData.details.forEach((item) => {
        if (item.callOffDutyBool) item.callOffDuty = 1;
        else item.callOffDuty = 0;
      });
      await request({
        url: "/andon/andcallsettingdetail/saveDetail",
        method: "post",
        data: { ...formData, infos: formData.details },
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/andon/andcallsettingdetail/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  sondetails.data.forEach((item) => {
    if (item.callOffDuty == "1") item.callOffDutyBool = true;
    else item.callOffDutyBool = false;
    if (item.userId) {
      item.users = [{ id: item.userId, personName: item.userName }];
    }
  });
  formData.details = sondetails.data;
}

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

/** 修改升级顺序 */
function changeDetailsSort(data) {
  let index = 0;
  formData.details.forEach((item) => {
    if (item.callSequence == data.callSequence) {
      index++;
    }
  });

  if (index > 1) {
    data.callSequence = "";
    return ElMessage.error("呼叫顺序号重复");
  }

  formData.details.sort((a, b) => a.callSequence - b.callSequence);
}

const memberRoleList: any = ref([]);
const memberRole = async () => {
  await request({
    url: "mes/mesmemberrole/getList",
    method: "post",
    data: {
      enabled: 1,
    },
  }).then((res) => {
    memberRoleList.value = res.data;
  });
};

function getDayPerson(Ids: string[], Objects: any, index) {
  if (Objects.length > 0) {
    formData.details[index].userId = Objects[0].id;
    formData.details[index].userName = Objects[0].personName;
  } else {
    formData.details[index].userId = "";
    formData.details[index].userName = "";
  }
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}

:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}

:deep.el-input.el-input--default.el-input--suffix {
  // 固定宽度
  width: 190px !important;
}
</style>
